import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/utils/api'

export const useHealthStore = defineStore('health', () => {
  const articles = ref([])
  const healthRecords = ref([])
  const menstrualCycles = ref([])
  const loading = ref(false)

  // 初始化应用
  const initApp = async () => {
    await Promise.all([
      fetchArticles(),
      fetchHealthRecords(1), // 假设用户ID为1
      fetchMenstrualCycles(1)
    ])
  }

  // 获取养生文章
  const fetchArticles = async () => {
    try {
      loading.value = true
      const response = await api.get('/articles')
      articles.value = response.data
    } catch (error) {
      console.error('获取文章失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取健康记录
  const fetchHealthRecords = async (userId) => {
    try {
      const response = await api.get(`/health-records/user/${userId}`)
      healthRecords.value = response.data
    } catch (error) {
      console.error('获取健康记录失败:', error)
    }
  }

  // 添加健康记录
  const addHealthRecord = async (record) => {
    try {
      const response = await api.post('/health-records', record)
      healthRecords.value.unshift(response.data)
      return response.data
    } catch (error) {
      console.error('添加健康记录失败:', error)
      throw error
    }
  }

  // 获取经期记录
  const fetchMenstrualCycles = async (userId) => {
    try {
      const response = await api.get(`/menstrual-cycles/user/${userId}`)
      menstrualCycles.value = response.data
    } catch (error) {
      console.error('获取经期记录失败:', error)
    }
  }

  // 添加经期记录
  const addMenstrualCycle = async (cycle) => {
    try {
      const response = await api.post('/menstrual-cycles', cycle)
      menstrualCycles.value.unshift(response.data)
      return response.data
    } catch (error) {
      console.error('添加经期记录失败:', error)
      throw error
    }
  }

  return {
    articles,
    healthRecords,
    menstrualCycles,
    loading,
    initApp,
    fetchArticles,
    fetchHealthRecords,
    addHealthRecord,
    fetchMenstrualCycles,
    addMenstrualCycle
  }
})
